// 此文件用于进行路由的配置

import Vue from "vue";
// 1.导入vue-router组件
import VueRouter from "vue-router";

import Login from "@/views/Login.vue";
import Home from "@/views/Home.vue";

import User from "@/components/menu/MyUser.vue";
import Goods from "@/components/menu/MyGoods.vue";
import Setting from "@/components/menu/MySetting.vue";
import Right from "@/components/menu/MyRights.vue";
import Order from "@/components/menu/MyOrder.vue";

import UserDetail from "@/components/user/MyUserDetail.vue";
// 2.把 VueRouter 安装为 Vue 项目的插件
Vue.use(VueRouter);

//3. 定义路由表
// routes 是一个数组，作用：定义 “hash 地址” 与 “组件” 之间的对应关系
const routes = [
  //登录重定向
  {
    path: "/",
    redirect: "/login",
  },
  // 登录的路由规则

  {
    path: "/login",
    component: Login,
  },
  {
    path: "/home",
    component: Home,
    //路由地址重定向
    redirect: "/home/user",
    //子级
    children: [
      { path: "user", component: User, },
      { path: "goods", component: Goods, },
      { path: "setting", component: Setting, },
      { path: "right", component: Right, },
      { path: "order", component: Order, },
      //用户详情页的路由规则
      { path: 'userinfo', component: UserDetail, },
    ]
  },
];

// 4. 创建router（路由管理器）的实例对象
const router = new VueRouter({
  routes,
});
//全局前置守卫
router.beforeEach((to, from, next) => {
  var pathArr = ['/home', '/home/user', '/home/right', '/home/goods', '/home/order', '/home/setting']
  if (pathArr.indexOf(to.path) != -1) {
    const token = window.sessionStorage.getItem('token');
    if (token) {
      next();
    } else {
      next('/login');
    }
  } else {
    next();
  }
});

//5.导出router路由管理对象
export default router;
